package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author kcs
 * @date 2021/11/25
 * @TIME:9:52
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class UploadController {

    @Value("${reggie.path}")
    private String path;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {

        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        //获取原始文件名
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));//后缀名

        //生成新的全球唯一文件名
        String name = UUID.randomUUID().toString().replace("-", "");

        //拼接新的文件名
        filename = name + suffix;
        log.info("新文件名:"+filename);

        //创建一个文件夹
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //将文件写入到本地指定位置
        //注意:transferTo必须使用绝对路径,如果想写入到项目位置,可以使用FileOutputStream
        file.transferTo(new File(path+filename));


        //方式2.使用FileOutputStream写入到项目位置
        /*InputStream is = file.getInputStream();
        FileOutputStream fos = new FileOutputStream(".\\"+filename);
        while (true){
            int read = is.read();
            if(read == -1){
                break;
            }
            fos.write(read);
        }*/

        return R.success(filename);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {

        log.info("开始下载菜品图片...");

        //输入流，通过输入流读取文件内容
        FileInputStream fileInputStream = new FileInputStream(path+name);

        //输出流，通过输出流将文件写回浏览器
        ServletOutputStream outputStream = response.getOutputStream();

        //返回给前端的是一个图片
        response.setContentType("image/jpeg");

        //进行读写
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }

        //关闭流
        fileInputStream.close();
        outputStream.close();
    }

}
